import { getAllRights,getAllRoles,postUpdateRights,deleteRolesRights} from '@/api/role'

const state={
    //所有一级角色
    AllRoles:[],
    //所有权限
    AllRights:[],
    //当前选中的角色
    currentRoles:{},
    //当前需要选中的id
    checked_keys:[],
    //整个tree树
    tree:{}

};
const getters={
    //获取当前需要选中的id
    get_checked_keys(state,getters,root){
        //console.log(getters.get_checked_keys);
        const arr=[];
        const  fn=(parent)=>{
            if(Array.from(parent)){
                parent.forEach((element)=>{
                    if(element.children) fn(element.children);
                    if(element.id) arr.push(element.id)
                })
            }
        }
        fn(state.currentRoles.children)
        return arr
      /*  state.currentRoles.children.forEach(ele => {
           ele.children.forEach( ele =>{
               ele.children.map( item =>{
                     console.log(item.id)
               })
           });
       } ); */
        
    }
    
};
const mutations={
    CHANGE_CURRENTROLES(state,playload){
        state.currentRoles=playload
    },
    CHANGE_AllRights(state,playload){
        state.AllRights=playload
    },
    CHANGE_CHEACKED_KEYS(state,playload){
        state.checked_keys=playload
    },
    CHANGE_TREE_OBJECT(state,playload){
        state.tree=playload
    }
};
const actions={
    //所有权限列表(list/tree)
    Acs_getAllRights(content,playload){
        return new Promise((resolve,reject)=>{
            getAllRights(playload)
            .then(res=>{
                    if(playload==='tree'){
                        //console.log(content);
                        content.commit('CHANGE_AllRights',res);  
                    }
                    resolve(res)
                }
            )
            .catch(err=>{
                reject(err)
            })
        })
    },
    //所有角色列表
    Acs_getAllRoles(content){
        return new Promise((resolve,reject)=>{
            getAllRoles()
            .then(res=>{
                    content.state.AllRoles=res;
                    resolve(res)
                }
            )
            .catch(err=>{
                reject(err)
            })
        })
    },
    //角色授权
    Acs_postUpdateRights(content,playload){
        return new Promise((resolve,reject)=>{
            postUpdateRights(playload)
            .then(res=>{
                    resolve(res)
                }
            )
            .catch(err=>{
                reject(err)
            })
        })
    },
    //删除角色指定权限
    Acs_deleteRolesRights(content,playload){
        return new Promise((resolve,reject)=>{
            deleteRolesRights(playload)
            .then(res=>{resolve(res)})
            .catch(err=>{
                reject(err)
            })
        })
    }
};
export default {
    namespaced:true,
    state,
    getters,
    mutations,
    actions
}
